<script setup lang="ts">
import FileSelector from './FileSelector.vue'
import CodeMirror from '../codemirror/CodeMirror.vue'
import Message from '../Message.vue'
import { debounce } from '../utils'
import { computed, inject, ref } from 'vue'
import { Store } from '../store'
const codeMirror = ref(null)
const store = inject('store') as Store
const emit = defineEmits<(e: 'run', value: string) => void>()
const onChange = debounce((code: string) => {
  store.state.activeFile.code = code
}, 250)

const activeMode = computed(() => {
  const { filename } = store.state.activeFile
  return filename.endsWith('.vue') || filename.endsWith('.html')
    ? 'htmlmixed'
    : filename.endsWith('.css')
    ? 'css'
    : 'javascript'
})
</script>

<template>
  <FileSelector
    @run="
      () => {
        emit('run')
      }
    "
  />
  <div class="editor-container">
    <CodeMirror
      ref="codeMirror"
      :value="store.state.activeFile.code"
      :mode="activeMode"
      @change="onChange"
    />
    <Message :err="store.state.errors[0]" />
  </div>
</template>

<style scoped>
.editor-container {
  height: calc(100% - var(--header-height));
  overflow: hidden;
  position: relative;
}
</style>
